package com.ywc.tools.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

public abstract class ListAdapter<T> extends BaseAdapter{
    private List<T> listData;
    private Context context;
    private int layoutId;
    public Context getContext() {
        return context;
    }

    public T obtainT(int position)
    {
        return listData.get(position);
    }

    public ListAdapter(Context context, int layoutId) {
        this.listData = new ArrayList<>();
        this.context = context;
        this.layoutId = layoutId;
    }

    @Override
    public int getCount() {
        return listData.size();
    }

    @Override
    public Object getItem(int position) {
        return listData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        BaseViewHold baseViewHold=null;
        if (convertView==null)
        {
            convertView=LayoutInflater.from(context).inflate(layoutId, null);
            baseViewHold=new BaseViewHold(convertView);
            convertView.setTag(baseViewHold);
        }
        else
        {
            baseViewHold= ((BaseViewHold) convertView.getTag());
        }
        setData(position,baseViewHold,obtainT(position));
        return convertView;
    }

    public abstract void setData(int position,BaseViewHold baseViewHold,T t);

    public void flush(List<T> listData)
    {
        if (this.listData.size()>0)
            this.listData.clear();
        this.listData.addAll(listData);
        notifyDataSetChanged();
    }

}
